package com.xja.shoppingmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.xja.shoppingmall.dao.OrderInfoRepository;
import com.xja.shoppingmall.entity.OrderInfo;
import com.xja.shoppingmall.goods.GoodsVo;
import com.xja.shoppingmall.goods.client.GoodsFeignClient;
import com.xja.shoppingmall.service.OrderService;
import com.xja.shoppingmall.util.TokenParseUtil;
import com.xja.shoppingmall.vo.CommonResponseVO;
import com.xja.shoppingmall.vo.LoginUserInfo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author CHENCHEN
 * @title
 * @createTime 2021-12-1519:44
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderInfoRepository orderInfoRepository;

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String createOrder(String token, Long goodsId) throws Exception {
        LoginUserInfo loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
        log.info("loginUserInfo : [{}]", JSON.toJSONString(loginUserInfo));
        Integer count = 1;
        //发送减库存
        GoodsVo goodsVo = new GoodsVo(goodsId, count.longValue(), null);
        CommonResponseVO commonResponseVO = goodsFeignClient.updateGoodsCount(goodsVo);
        log.info("修改库存结果为：[{}]", JSON.toJSONString(commonResponseVO));
        //创建订单
        OrderInfo orderInfo = new OrderInfo(null, UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16), "0", loginUserInfo.getId());
        OrderInfo save = orderInfoRepository.save(orderInfo);
        log.info("添加订单的结果是：[{}]", JSON.toJSONString(save));
        if(commonResponseVO.getData() instanceof Boolean){
            throw new RuntimeException("假如抛出异常....");
        }
        return "修改库存结果为： " + JSON.toJSONString(commonResponseVO) + ", 添加订单的结果是：" + JSON.toJSONString(save);
    }
}
